package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.DeleteOrderListener;
import com.zl.smartmall.library.listener.GetOrdersListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.OrdersInfo;
import com.zl.smartmall.library.po.OrdersProductInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

public class MyOrders extends BaseActivity implements OnItemClickListener,OnRefreshListener<ListView>, OnFooterViewRefreshListener, OnLoadingCoverRefreshListener {
	private static final String TAG = MyOrders.class.getSimpleName();	
	
	private PullToRefreshListView mPullList;

	private MyHandler mHandler;
	private List<OrdersInfo> mOrdersInfos;
	private MyAdapter mAdapter;
	private LayoutInflater mInflater;
	private DisplayImageOptions options;
	private List<String> mDeleteOrderCodes;
	
	private LoadingCover mLoadingCover;
	private OfflineDialog mOfflineDialog;
	private FooterView mFooterView;
	private Dialog mMenudialog;
	private TextView mTvTitle;
	private Dialog mLoadingData;
	private Button btn_change;//确认按钮
	OrdersInfo ordersInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_orders);
		
		mOrdersInfos = new ArrayList<OrdersInfo>();
		mHandler =  new MyHandler(this);
		mInflater = getLayoutInflater();
		mAdapter = new MyAdapter();
		options = buildOptions();
		mDeleteOrderCodes = new ArrayList<String>();
			
//		setActionbarTitle("我的订单", false);
		setActionbarTitle(getIntent().getStringExtra("name"), false);
		mPullList = (PullToRefreshListView) findViewById(R.id.list_orders);
		mPullList.setAdapter(mAdapter);
		mPullList.setOnItemClickListener(this);
		mPullList.setOnRefreshListener(this);
		
		mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		mPullList.getRefreshableView().addFooterView(mFooterView);
		mPullList.setOnScrollListener(mFooterView);
		
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mOfflineDialog = (OfflineDialog) getLayoutInflater().inflate(R.layout.offline_dialog, null);
		
		mLoadingData = new Dialog(this, R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog2);
		mLoadingData.setCancelable(false);
		mLoadingData.setCanceledOnTouchOutside(false);
		
		onLoadingCoverRefresh();
	}

	
	private GetOrdersListener buildListener(RequestCode requestCode) {
		return new GetOrdersListener(requestCode) {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				mFooterView.onRefreshFailed();
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				 
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
				mFooterView.onRefreshFailed();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				mFooterView.onRefreshComplete();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_MORE_DATA);
			}
			
			@Override
			public void onResponseSuccess(List<OrdersInfo> ordersInfos) {
				// TODO Auto-generated method stub
				if(getRequestCode() == RequestCode.PULL) {
					mOrdersInfos.clear();
				}
				mOrdersInfos.addAll(ordersInfos);
				mAdapter.notifyDataSetChanged();
				if(ordersInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE){
					mFooterView.onRefreshComplete();
					mPullList.setOnScrollListener(null);
				}else {
					mFooterView.onRefreshSuccess();
					mPullList.setOnScrollListener(mFooterView);
				}
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				mLoadingCover.onRefreshSuccess();
			}
		};
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.release();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(view == mFooterView){
			return;
		}
		Intent intent = new Intent(getApplicationContext(), OrderDetail.class);
		intent.putExtra("sn", mOrdersInfos.get((int)id).getOrderNumber());
		CrashHandler.d(TAG, "sn:"+mOrdersInfos.get((int)id).getOrderNumber());
		CrashHandler.d(TAG, "id:"+id);
		CrashHandler.d(TAG, "position:"+position);
		startActivityForResult(intent, Define.ACTIVITY_CODE_ORDER_DETAIL);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case Define.ACTIVITY_CODE_ORDER_CANCEL:
		case Define.ACTIVITY_CODE_ORDER_PAID:
		case Define.ACTIVITY_CODE_ORDER_SIGN:
		case Define.ACTIVITY_CODE_APPLY_EXCHANGE:
			mPullList.setRefreshing();
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
//		Tools.recordBehavious(getApplicationContext(), TAG , Define.BEHAVIOUS_RESUME);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
//		Tools.recordBehavious(getApplicationContext(), TAG, Define.BEHAVIOUS_PAUSE);
	}


	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getOrders(mOrdersInfos.get(mOrdersInfos.size() - 1).getOrderId(),
				getIntent().getStringExtra("orderType"), 
				buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getOrders(0, getIntent().getStringExtra("orderType"), buildListener(RequestCode.PULL));
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getOrders(0, getIntent().getStringExtra("orderType"), buildListener(RequestCode.PULL));
	}
	
	private DisplayImageOptions buildOptions() {
		return new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.drawable.ic_load_image_square_default)
        .showImageOnFail(R.drawable.ic_load_image_square_fail)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
        .displayer(new RoundedBitmapDisplayer(5))
        .build();
	}
	
	private DeleteOrderListener buildDeleteOrderListener() {
		return new DeleteOrderListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "订单删除失败, 请重试");
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				OrdersInfo tempOrdersInfo = null;
				for(OrdersInfo ordersInfo : mOrdersInfos) {
					if(ordersInfo.getOrderNumber().equals(getOrderCode())) {
						tempOrdersInfo = ordersInfo;
					}
				}
				if(tempOrdersInfo != null) {
					mOrdersInfos.remove(tempOrdersInfo);
					mAdapter.notifyDataSetChanged();
				}
			}
			
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish();
				mDeleteOrderCodes.remove(getOrderCode());
			}
		};
	}
	
	private static class MyHandler extends Handler {

		private MyOrders mOuter;

		public MyHandler(MyOrders outer) {
			mOuter = outer;
		}

		public void handleMessage(android.os.Message msg) {
			if (mOuter == null) {
				return;
			}
			switch (msg.what) {
			case 1://刷新adapter
				mOuter.mAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		};

		public void release() {
			new WeakReference<MyOrders>(mOuter);
		}
	};

	private class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return mOrdersInfos.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mOrdersInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.myorders_item_v2, null);
				holder = new ViewHolder();
				holder.createTime = (TextView) convertView.findViewById(R.id.tv_create_time);
				holder.orderNumber = (TextView) convertView.findViewById(R.id.tv_order_number);
				holder.status = (TextView) convertView.findViewById(R.id.tv_status);
				holder.receiverName = (TextView) convertView.findViewById(R.id.tv_receiver_name);
				holder.listProducts = (LinearLayout) convertView.findViewById(R.id.list_products);
				holder.payMoney = (TextView) convertView.findViewById(R.id.tv_pay_money);
				holder.productNum = (TextView) convertView.findViewById(R.id.tv_product_num);
				holder.trashcan = convertView.findViewById(R.id.iv_delete);
				//点击删除按钮，删除相应的订单
				holder.trashcan.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						ordersInfo = (OrdersInfo) v.getTag();
						createDialog();
					}
				});
				convertView.setTag(holder);
				
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			OrdersInfo ordersInfo = mOrdersInfos.get(position);
//			holder.createTime.setText(Tools.format2ChineseDate(info.getCreateTime()));
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			holder.createTime.setText(format.format(new Date(ordersInfo.getCreateTime()*1000)));
			holder.orderNumber.setText("订单号：" + ordersInfo.getOrderNumber());
			holder.receiverName.setText(ordersInfo.getReceiverName());
			holder.payMoney.setText("￥" + new DecimalFormat("0.00").format(ordersInfo.getMoney()));
			holder.productNum.setText("共" + ordersInfo.getOrdersProductInfos().size() + "件商品");
			holder.trashcan.setTag(ordersInfo);
			holder.trashcan.setVisibility(View.GONE);
			//是否退换货，退换货显示处理状态，否则显示支付状态
			if(ordersInfo.getIsReturn() != 0 && ordersInfo.getStatus() != Define.ORDER_STATUS_CANCEL
					&& ordersInfo.getStatus() != Define.ORDER_STATUS_INVALIDATE
					&& ordersInfo.getStatus() != Define.ORDER_STATUS_SIGN_IN) {
				String action = ordersInfo.getIsReturn() == 1 ? "退货" : "换货";
				switch (ordersInfo.getReturnStatus()) {
				case 1:
					holder.status.setText(action + "审核中");
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
					break;

				case 2:
					holder.status.setText(action + "处理中");
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
					break;
					
				case 3:
					holder.status.setText(action + "被驳回");
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
					break;
					
				case 4:
					holder.status.setText(action + "成功");
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
					break;
				}
				
			}else {
				switch (ordersInfo.getStatus()) {//# 订单状态，0未支付，1支付成功，2已发货，4完成(签收)，5已失效(过期未支付)，6订单取消
				case Define.ORDER_STATUS_NO_PAY:
					holder.status.setText(Define.ORDER_STATUS_NO_PAY_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_no_pay));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_red);
					break;
					
				case Define.ORDER_STATUS_PAID:
					holder.status.setText(Define.ORDER_STATUS_PAID_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
					break;
					
				case Define.ORDER_STATUS_DELIVERIED:
					holder.status.setText(ordersInfo.getDeliveryWay() == Constants.PAY_ON_DELIVERY ? Define.ORDER_STATUS_DELIVERIED_TEXT :
						Define.ORDER_STATUS_TAKE_SELF_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
					break;
					
				case Define.ORDER_STATUS_SIGN_IN:
					holder.status.setText(Define.ORDER_STATUS_SIGN_IN_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_trade_successful));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
					//显示垃圾桶
					holder.trashcan.setVisibility(View.VISIBLE);
					break;
					
				case Define.ORDER_STATUS_INVALIDATE:
					holder.status.setText(Define.ORDER_STATUS_INVALIDATE_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.RGB_A8A8A8));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
					//显示垃圾桶
					holder.trashcan.setVisibility(View.VISIBLE);
					break;
					
				case Define.ORDER_STATUS_CANCEL:
					holder.status.setText(Define.ORDER_STATUS_CANCEL_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.RGB_A8A8A8));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
					//显示垃圾桶
					holder.trashcan.setVisibility(View.VISIBLE);
					break;
					
				case Define.ORDER_STATUS_STOCK_UP:
					holder.status.setText(Define.ORDER_STATUS_STOCK_UP_TEXT);
					holder.status.setTextColor(getResources().getColor(R.color.text_color_my_order_payed));
					holder.status.setBackgroundResource(R.drawable.bg_my_orders_frame_green);
					break;
	
				default:
					break;
				}
			}
			
			List<OrdersProductInfo> ordersProductInfos = ordersInfo.getOrdersProductInfos();
			holder.listProducts.removeAllViews();
			for(int i = 0; i < ordersProductInfos.size(); i++){
				OrdersProductInfo ordersProductInfo = ordersProductInfos.get(i);
				View view = mInflater.inflate(R.layout.myorders_item_products_item, null);
				((TextView)view.findViewById(R.id.tv_product_title)).setText(ordersProductInfo.getProductTitle());
				((TextView)view.findViewById(R.id.tv_product_price)).setText(ordersProductInfo.getTagPrice()+"");
				((TextView)view.findViewById(R.id.tv_buy_num)).setText("数量：" + ordersProductInfo.getBuyNum());
				ImageLoader.getInstance().displayImage(ordersProductInfo.getIcon(), (ImageView) view.findViewById(R.id.iv_product_pic), options);
				holder.listProducts.addView(view);
				View divider = view.findViewById(R.id.divider);
				if(i == ordersProductInfos.size() - 1) {
					((LinearLayout.LayoutParams) divider.getLayoutParams()).leftMargin = 0;
				}else {
					((LinearLayout.LayoutParams) divider.getLayoutParams()).leftMargin = 
							Tools.dip2px(getApplicationContext(), 15);
				}
			}
			return convertView;
		}
		
	}
	private class ViewHolder{
		TextView createTime;
		TextView orderNumber;
		TextView status;
		TextView receiverName;
		TextView payMoney;
		TextView productNum;
		LinearLayout listProducts;
		View trashcan;
	}
	//订单删除确认操作
	private void createDialog() {
		mMenudialog = new Dialog(this, R.style.DialogTheme);
		View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.mycommunity_dialog_layout, null);
		mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
		mTvTitle.setText("确认删除订单");
		btn_change = (Button) dialogView.findViewById(R.id.btn_change);
		btn_change.setText("确认");
		btn_change.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//mLoadingData.show();
				if(!mDeleteOrderCodes.contains(ordersInfo.getOrderNumber())) {
					ISmartMall.getInstance().deleteOrder(ordersInfo.getOrderNumber(), buildDeleteOrderListener());
					
				}
				mMenudialog.dismiss();
			}
		});
		dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mMenudialog.dismiss();
			}
		});
		mMenudialog.setContentView(dialogView);
		mMenudialog.setCancelable(false);
		mMenudialog.setCanceledOnTouchOutside(false);
		mMenudialog.show();
	}
	
	
}
